package xuhaijia.lanou3g.autohome.activity;
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                   \\`.
//        .'//            为什么坚持  想一想当初             \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-.  \\`.
//    .'//.-"                 `-.  |  .-'                 "-. \\`.
//  .'//______.============-..   \ | /   ..-============._______\\`.
//.'//____________________________\|/_____________________________\\`.
// 
//                             

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import xuhaijia.lanou3g.autohome.R;

/**
 * Created by 7 on 16/8/30.
 */
public class PlayService extends Service {
    MediaPlayer mediaPlayer;
    private NotificationManager notificationManager;
    private NotificationManagerCompat notificationManagerCompat;
    private final static String play = "autohome.radio.PLAY";
    private final static String close = "autohome.radio.CLOSE";
    private RemoteViews remoteViews;
    private Notification notify;

    public void setRemoteViews(RemoteViews remoteViews) {
        this.remoteViews = remoteViews;
    }

    public RemoteViews getRemoteViews() {
        return remoteViews;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManagerCompat = NotificationManagerCompat.from(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(play);
        filter.addAction(close);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onDestroy() {
        // EventBus 在使用完成后需要取消注册
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mReceiver);
        super.onDestroy();

    }

    @Subscribe()
    public void getData(RadioEvent radioEvent) {
        // 取出数据,设置到TextView上
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(PlayService.this, Uri.parse(radioEvent.getUrl()));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        showNotify();
    }

    private void showNotify() {
        // 2.获取Notifycation对象
        notify = createNotify();

        // 设置Notification 不能滑动删除 只能通过代码取消通知
        notify.flags = Notification.FLAG_NO_CLEAR;

        // 3.通过Manager显示Notification
        // 参数一: 用来区分不同的通知 如果id值不变 则只显示一个通知
//        notifyManager.notify(i++ ,notify);
        // 兼容性更高
//        notificationManagerCompat.notify(7, notify);
        startForeground(7, notify);

    }

    private Notification createNotify() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        // builder 可用链式 写法 因为返回值都是this;

        builder.setSmallIcon(R.mipmap.ahlib_about_icon_logo);

        // 设置来通知的时候 声音/ 震动 /三色灯的显示
//        builder.setDefaults(Notification.DEFAULT_ALL);

        // 设置点击Notification之后, 通知消失
        builder.setAutoCancel(true);

        // 为Notification设置点击事件
//        PendingIntent intent = getPendingIntent();
//        builder.setContentIntent(intent);
        //  为通知设置自定义布局
        RemoteViews views = getViews();
//        views.setImageViewResource();
        builder.setContent(views);
        return builder.build();

    }

    public RemoteViews getViews() {
        remoteViews = new RemoteViews(getPackageName(), R.layout.remote_notify);
        PendingIntent preIntentPlay = PendingIntent.getBroadcast(this, 101, new Intent(play), PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.remote_notify_play, preIntentPlay);
        PendingIntent preIntentClose = PendingIntent.getBroadcast(this, 102, new Intent(close), PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.remote_notify_close, preIntentClose);

        return remoteViews;
    }

    //    public PendingIntent getPendingIntent() {
//        return pendingIntent;
//    }
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case play:
                    if (mediaPlayer.isPlaying()) {
                        Log.d("PlayService", "暂停");
                        mediaPlayer.pause();
                        remoteViews.setImageViewResource(R.id.remote_notify_play, R.mipmap.play);
                    } else {
                        Log.d("PlayService", "播放");
                        mediaPlayer.start();
                        remoteViews.setImageViewResource(R.id.remote_notify_play, R.mipmap.stop);
                    }
                    startForeground(7, notify);
                    break;
                case close:
                    stopSelf();
                    break;
            }
        }
    };
}
